<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" class="addRole" @click="addroles">添加角色</el-button>
        </el-col>
      </el-row>
      <template>
        <el-table style="width: 100%" border :data="rolelist" stripe>
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['bdbottom', i1==0?'bdtop':'','vcenter']"
                v-for="(item1,i1) in scope.row.children"
                :key="item1.id"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag closable>{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <el-row
                    :class="['bdtop', i2==0?'bdstop':'','vcenter']"
                    v-for="(item2,i2) in item1.children"
                    :key="item2.id"
                  >
                    <!-- 二级循环 -->
                    <el-col :span="6">
                      <el-tag closable type="success">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级循环 -->
                    <el-col :span="18">
                      <el-tag
                        closable
                        type="warning"
                        v-for="(item3) in item2.children"
                        :key="item3.id"
                        @close="removeRightById(scope.row,item3.id)"
                      >{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述" width="180"></el-table-column>
          <el-table-column prop="level" label="操作">
            <template slot-scope="scope">
              <el-button
                @click="modifyrole(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="min"
              >编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="min">删除</el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="min"
                @click="Assignpermissions(scope.row)"
              >分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addroleVisible" width="50%" @close="addroleClose">
      <el-form :model="addroleForm" ref="addroleRefs" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addroleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addroleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色 -->
    <el-dialog title="修改角色" :visible.sync="modifyroleVisible" width="50%" @close="modifyroleClose">
      <el-form :model="modifyroleForm" ref="addroleRefs" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifyroleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="modifyroleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyroleVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="提示" :visible.sync="distributeVisible" width="50%" @close="refreshmodify">
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key='id' default-expand-all :default-checked-keys='keys'	ref="treeRefs"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="distributeVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolelist: [],
      //   添加角色默认隐藏
      addroleVisible: false,
      //   修改角色默认隐藏
      modifyroleVisible: false,
      //   分配角色默认隐藏
      distributeVisible: false,
      addroleForm: {
        roleName: "",
        roleDesc: ""
      },
      modifyroleForm: {},
      rightList: [],
      treeProps:{
          label:'authName',
          Children: 'children'
      },
      keys:[],
      RoleId:''
    };
  },
  created() {
    this.getrolelist();
  },
  methods: {
    async getrolelist() {
      const { data: res } = await this.$http.get("roles");
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.$message.success("更新角色列表成功");
      this.rolelist = res.data;
      // console.log(this.rolelist);
    },
    addroles() {
      this.addroleVisible = true;
    },
    //   关闭添加角色界面并重置
    addroleClose() {
      this.$refs.addroleRefs.resetFields();
    },
    //   关闭修改角色界面并重置
    modifyroleClose() {
      this.$refs.addroleRefs.resetFields();
    },
    //   添加角色
    async addUser() {
      const { data: res } = await this.$http.post("roles", this.addroleForm);
      console.log(res);
      this.addroleVisible = false;
      this.getrolelist();
    },
    // 编辑角色点击事件
    async modifyrole(id) {
      this.modifyroleVisible = true;
      const { data: res } = await this.$http.get("roles/" + id);
      console.log(res);
      this.modifyroleForm = res.data;
    },
    async modifyUser() {
      const { data: res } = await this.$http.put(
        "roles/" + this.modifyroleForm.roleId,
        {
          roleName: this.modifyroleForm.roleName,
          roleDesc: this.modifyroleForm.roleDesc
        }
      );
      this.modifyroleVisible = false;
      this.getrolelist();
      console.log(res);
    },
    // 删除权限
    async removeRightById(role, rightId) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(res);
      if (res !== "confirm") {
        return this.$message.info("您已取消删除");
      }
      const { data: result } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      console.log(result);

      if (result.meta.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      // this.$message.success('删除权限成功')
      role.children = result.data;
    },
    // 分配权限
    async Assignpermissions(role) {
        this.RoleId=role.id
        // console.log(role);
      this.distributeVisible = true;
      const { data: res } = await this.$http.get("rights/tree");
    //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.rightList = res.data;
      this.getleafkeys(role,this.keys)
    //   console.log(this.rightList);
    },
    // 通过递归，获取三级权限下的所有的id，并保存到keys数组中
    getleafkeys(node,arr){
        // node为节点,如果node不含children则为三级节点
        if(!node.children){
           return arr.push(node.id)
        }
        node.children.forEach(item => {
            this.getleafkeys(item,arr)
        });
    },
    refreshmodify(){
        this.keys=[];
    },
   async allotRights(){
        const keies=[
            ...this.$refs.treeRefs.getCheckedKeys(),
            ...this.$refs.treeRefs.getHalfCheckedKeys()
        ]
        const idStr=keies.join(',')
       const {data:res}=await this.$http.post(`roles/${this.RoleId}/rights`,{rids:idStr})
       console.log(res);
       if(res.meta.status!==200){
           return this.$message.error('分配权限失败')
       }
       this.$message.success('分配权限成功')
       this.getrolelist()
       this.distributeVisible=false
    }
  }
};
</script>
<style lang="less" scoped>
.addRole {
  margin-bottom: 10px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdstop {
  border-top: 0 none;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>